package com.bwie.service.Impl;

import cn.hutool.captcha.generator.RandomGenerator;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.domain.SendPhone;
import com.bwie.poi.StringUtils;
import com.bwie.service.SendPhoneService;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginUser;
import com.mchange.v2.lang.ObjectUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jodd.util.StringUtil;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.UserMapper;
import com.bwie.domain.User;
import com.bwie.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static cn.hutool.core.date.DateUtil.now;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private SendPhoneService sendPhoneService;

    @Override
    public R checkPhone(LoginUser loginUser) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserPhone, loginUser.getUserPhone());
        User one = getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            return R.ERROR(500, "手机号不存在&未注册");
        }
        return R.OK();
    }

    @Override
    public R sendPhoneCode(LoginUser loginUser) {
        if (StringUtils.isEmpty(loginUser.getUserPhone())) {
            return R.ERROR(500, "请填写手机号，手机号不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserPhone, loginUser.getUserPhone());
        User one = getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            return R.ERROR(500, "手机号不存在&未注册");
        }
        String SendCodeSuccess = "SendCodeSuccess" + loginUser.getUserPhone();
        String RedisPhoeCode = redisTemplate.opsForValue().get(SendCodeSuccess);
        if (StringUtils.isNotEmpty(RedisPhoeCode)) {
            return R.ERROR(500, "验证码一个手机号5分钟只能发送1次");
        }
        String code = new RandomGenerator("123456789", 4).generate();
        Boolean b = MobileMessageUtil.sendMobileMessage(loginUser.getUserPhone(), code);
        if (b) {
            redisTemplate.opsForValue().set(SendCodeSuccess, code, 5, TimeUnit.MINUTES);
            sendPhoneService.save(SendPhone.builder()
                    .sendPhoe(loginUser.getUserPhone())
                    .sendOkTime(String.valueOf(new DateTime()))
                    .sendStatus("发送成功")
                    .createTime(String.valueOf(new DateTime()))
                    .build());
            return R.OK();
        }
        sendPhoneService.save(SendPhone.builder()
                .sendPhoe(loginUser.getUserPhone())
                .sendOkTime(String.valueOf(new DateTime()))
                .sendStatus("发送失败")
                .createTime(String.valueOf(new DateTime()))
                .build());
        return R.ERROR(500, "发送验证码失败");
    }

    @Override
    public R LoginByPhone(LoginUser loginUser) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserPhone, loginUser.getUserPhone());
        User one = getOne(wrapper);
        if (ObjectUtil.isEmpty(one)) {
            return R.ERROR(500, "手机号输入错误");
        }
        String SendCodeSuccess = "SendCodeSuccess" + loginUser.getUserPhone();
        String RedisPhoeCode = redisTemplate.opsForValue().get(SendCodeSuccess);
        if (StringUtils.isEmpty(RedisPhoeCode)) {
            return R.ERROR(500, "手机号验证码不存在");
        }
        if (!RedisPhoeCode.equals(loginUser.getPhoeCode())) {
            return R.ERROR(500, "手机号验证码输入错误");
        }
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "Gpyo").claim("userId", one.getId()).compact();
        one.setToken(token);
        return R.OK(one);
    }
}
